package com.itheima.controller;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.entity.Employee;
import com.itheima.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService iEmployeeService;

    @GetMapping("/export")
    public void downloadData(HttpServletResponse response) {
        response.setHeader("Content-Disposition",
                "attachment; filename=employee.xlsx");
        List<Employee> list = iEmployeeService.list();
        for (int i = 0; i < list.size(); i++) {
            String name =list.get(i).getUsername();


        }

    }

    //用于完成用户登录的方法
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session) {
        if (employee == null || StringUtils.isEmpty(employee.getUsername()) || StringUtils.isEmpty(employee.getPassword())) {
            return R.error("用户名或者密码不能为空");
        }

        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.eq(Employee::getUsername, employee.getUsername());
        Employee one = iEmployeeService.getOne(qw);
        if (one.getStatus() == 0) {
            return R.error("账号已禁用");
        }

        String password = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        if (!(one.getPassword().equals(password))) {
            return R.error("密码错误");
        } else {
            session.setAttribute("LoginUser", one.getId());
            one.setPassword(null);
            return R.success(one);
        }

    }

    @PostMapping("/logout")
    public R<Employee> logout(HttpSession session) {
        //清理Session中保存的当前登录员工的id
        //session.invalidate();
        session.removeAttribute("LoginUser");
        return R.success(null);
    }

    @PostMapping
    public R addEmployee(@RequestBody Employee employee, HttpSession session) {
        //前端已经对数据进行校验了，这里只是对测试数据进行反馈。
        if (employee == null || StringUtils.isEmpty(employee.getUsername()) || StringUtils.isEmpty(employee.getName()) || StringUtils.isEmpty(employee.getPhone()) || StringUtils.isEmpty(employee.getSex()) || StringUtils.isEmpty(employee.getIdNumber())) {
            return R.error("请输入完整信息");
        }
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.eq(Employee::getUsername, employee.getUsername());
        Employee one = iEmployeeService.getOne(qw);

        if (one != null) {
            return R.error("用户名已存在");
        } else {
            //设置新用户的默认密码为123456，MD5加密
            employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
            //employee.setStatus(1);
            //SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //System.out.println(LocalDateTime.parse(SDF.format(System.currentTimeMillis())));
//            LocalDateTime dateTime = LocalDateTime.now(); // gets the current date and time
//            DateTimeFormatter formatter =jn("yyyy-MM-dd HH:mm:ss");
//            System.out.println(LocalDateTime.parse(dateTime.format(formatter)));
            employee.setCreateTime(LocalDateTime.now());
            employee.setUpdateTime(LocalDateTime.now());
            employee.setCreateUser((Long) session.getAttribute("LoginUser"));
            employee.setUpdateUser((Long) session.getAttribute("LoginUser"));
            iEmployeeService.save(employee);
        }

        return R.success(null);
    }

    @GetMapping("/page")
    public R<Map> pageQuery(Integer page, Integer pageSize, String name) {
        //1、分页参数封装  new Page<Employee>(当前页，每页大小)
        Page<Employee> pageInfo = new Page<>(page, pageSize);
//2、封装查询条件 new LambdaQueryWrapper() : where name like '%xxx%'
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
// like(条件,xx,xx)
        qw.like(!(StringUtils.isEmpty(name)), Employee::getName, name);
        //添加排序条件
//3、添加默认排序 orderByDesc() :  order by update_time desc
//        qw.orderByDesc(Employee::getUpdateTime);

        //执行查询
        iEmployeeService.page(pageInfo, qw);
        //列表数据
        List<Employee> records = pageInfo.getRecords();
        System.out.println(records);
        //总记录数
        long total = pageInfo.getTotal();
        HashMap<Object, Object> map = new HashMap<>();
        map.put("records", records);
        map.put("total", total);
        return R.success(map);

    }

    @PutMapping
    public R updateStatus(@RequestBody Employee employee, HttpSession session) {
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser((Long) session.getAttribute("LoginUser"));
        boolean b = iEmployeeService.updateById(employee);
        if (b) {
            return R.success("修改成功");
        } else {
            return R.error("修改失败");
        }

    }

    @GetMapping("/{id}")
    public R selectEmployeeById(@PathVariable Long id) {
        Employee one = iEmployeeService.getById(id);
        if (one != null) {
            return R.success(one);
        } else
            return R.error("修改失败");
    }

}
